package org.hackystat.linkedservicedata.ui.users;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import org.hackystat.linkedservicedata.client.LinkedServiceDataClient;
import org.hackystat.linkedservicedata.client.LinkedServiceDataClientException;
import org.hackystat.linkedservicedata.resource.linkedservicedata.LinkedServiceDataResource;
import org.hackystat.linkedservicedata.ui.LinkedServiceDataUI;
import org.hackystat.linkedservicedata.vocabularies.DoapVocab;
import org.hackystat.linkedservicedata.vocabularies.FoafVocab;
import org.hackystat.linkedservicedata.vocabularies.HackystatConstants;
import org.hackystat.linkedservicedata.vocabularies.HackystatVocab;
import org.hackystat.sensorbase.resource.users.jaxb.User;
import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.NodeIterator;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.rdf.model.StmtIterator;
import com.hp.hpl.jena.vocabulary.OWL;
import com.hp.hpl.jena.vocabulary.RDF;
import com.hp.hpl.jena.vocabulary.RDFS;

/**
 * Panel to list and edit all the projects.
 *
 * @author Myriam Leggieri.
 *
 */
public class UsersPanel extends JPanel implements KeyListener, ActionListener {

  /**
   * Prefix to identify that one of the 'edit' button has been pressed
   */
  private static final String EDITPREFIX = "EDIT_";

  /**
   * Prefix to identify that one of the 'triplify' button has been pressed
   */
  private static final String TRIPLIFYPREFIX = "TRIPLIFY_";

  /**
   * Prefix to identify that one of the 'save' button has been pressed
   */
  private static final String SAVEPREFIX = "SAVE_";

  /**
   * Prefix to identify that one of the 'ok' button has been pressed
   */
  private static final String OKPREFIX = "OK_";

  /** RDF model containing a list of registered users. */
  private Model usersListModel = null;

  /** List of RDF model containing registered users' profiles. */
  private LinkedList<Model> profilesModelList = null;

  /**
   * List of user profile's data. Each profile is associated with text fields containing its data
   * which will become editable if one requires to edit data.
   */
  private HashMap<UserProfile, LinkedList<JTextField>> profilesList = null;

  /** Parent frame. */
  private LinkedServiceDataUI mainframe = null;

  /** Dialog used for displaying the 'please wait' window. */
  private JDialog dialog = null;

  /** Clear cache button. */
  private JButton clearCacheButton = null;

  /**
   * Edit button. Each edit button will be associated with an action command starting with 'edit_'
   * and ending with the correspondent user profile's email
   */
  private JButton editButton = null;

  /** Triplify all button. */
  private JButton triplifyAllButton = null;

  /** Triplify one profile button. */
  private JButton triplifyOneButton = null;

  /** Action label. */
  private JLabel actionLabel = null;

  /** Email label. */
  private JLabel emailLabel = null;

  /** Nickname label. */
  private JLabel nickLabel = null;

  /** Skills label. */
  private JLabel skillsLabel = null;

  /** Karma label. */
  private JLabel karmaLabel = null;

  /** SeeAlso label. */
  private JLabel seeAlsoLabel = null;

  /** SameAs label. */
  private JLabel sameAsLabel = null;

  /** Projects roles label. */
  private JLabel projectsrolesLabel = null;

  /** Homepage label. */
  private JLabel homepageLabel = null;

  /** Weblog label. */
  private JLabel weblogLabel = null;

  /** NameSurname label. */
  private JLabel nameSurnameLabel = null;

  /** Visibility label. */
  private JLabel visibilityLabel = null;

  /** Visibility text. */
  private JTextField visibilityText = null;

  /** Email text. */
  private JTextField emailText = null;

  /** Nickname text. */
  private JTextField nickText = null;

  /** Homepage text. */
  private JTextField homepageText = null;

  /** Weblog text. */
  private JTextField weblogText = null;

  /** NameSurname text. */
  private JTextField nameSurnameText = null;

  /** Karma text. */
  private JTextField karmaText = null;

  /** Password text. */
  private JPasswordField passwordText = null;

  /** List of skills. */
  private JList listSkills = null;

  /** List of skills. */
  private JList listSeeAlso = null;

  /** List of skills. */
  private JList listSameAs = null;

  /** List of skills. */
  private JList listProjectsRoles = null;

  /** Profile Panels dimension. */
  // private Dimension profilePanelDimension = new Dimension(800, 200);
  /** Search button. */
  private JButton okButton = null;

  /** Search button. */
  private JButton searchButton = null;

  /** Refresh button. */
  private JButton refreshButton = null;

  /** Save button. */
  private JButton saveButton = null;

  /**
   * RDF serialization language used to obtain the currently displayed data.
   */
  private String language = null;

  /**
   * User (identified by its email) whose correspondent panel is currently in an editing mode.
   */
  private UserProfile userInEditingMode = null;

  private String password = "";

  /**
   * Auto-generated serial version ID
   */
  private static final long serialVersionUID = 2927369587956956550L;

  public UsersPanel(LinkedServiceDataUI mainframe) {
    this.mainframe = mainframe;
    resetPanel();
  }

  private void refreshProfiles() {
    profilesList = new HashMap<UserProfile, LinkedList<JTextField>>();
    profilesModelList = new LinkedList<Model>();
    userInEditingMode = null;
    disableAllJTextFields();
    displayWaitingDialog();
    LinkedList<JTextField> textlist = null;
    this.language = mainframe.getLiSeDClient().getLanguage();
    try {
      usersListModel = mainframe.getLiSeDClient().getUsersList();
      if (usersListModel != null) {
        LinkedServiceDataResource.printModel(usersListModel);
        NodeIterator nodit = usersListModel.listObjects();
        RDFNode nod = null;
        Model tmpModel = null;
        String useruri = null;
        while (nodit.hasNext()) {
          nod = nodit.next();
          if (nod.isLiteral()) {
            useruri = ((Literal) nod).getLexicalForm();
          }
          else if (nod.isResource() && !nod.isAnon()) {
            useruri = ((Resource) nod).getURI();
          }
          if (!useruri.equals(RDF.Bag.getURI()) && !useruri.endsWith("@hackystat.org")) {
            try {
              tmpModel = mainframe.getLiSeDClient().getUriUserAsLinkedData(useruri);
            }
            catch (LinkedServiceDataClientException e) {
              JOptionPane.showMessageDialog(this, "Unable to retrieve user profile for " + useruri
                  + ".", "Hackystat - Error Message", JOptionPane.ERROR_MESSAGE);
              tmpModel = null;
            }
            if (tmpModel != null) {
              profilesModelList.add(tmpModel);
            }
          }
        }
        StmtIterator it = null;
        UserProfile uprofile = null;
        Statement statement = null;
        Property predicate = null;
        String object = null;
        for (Model model : profilesModelList) {
          it = model.listStatements();
          uprofile = new UserProfile();
          while (it.hasNext()) {
            statement = it.next();
            predicate = statement.getPredicate();
            nod = statement.getObject();
            if (nod.isLiteral()) {
              object = ((Literal) nod).getLexicalForm();
            }
            else if (nod.isResource() && !nod.isAnon()) {
              object = ((Resource) nod).getURI();
            }
            if (predicate.equals(FoafVocab.MBOX)) {
              uprofile.email = object;
            }
            else if (predicate.equals(FoafVocab.NICK)) {
              uprofile.nickname = object;
            }
            else if (predicate.equals(FoafVocab.HOMEPAGE)) {
              uprofile.homepage = object;
            }
            else if (predicate.equals(HackystatVocab.AMOUNT_OF_CODE_ISSUES)) {
              uprofile.setAmountOfIssues(Double.valueOf(String.valueOf(object)));
            }
            else if (predicate.equals(HackystatVocab.BUILD_QUALITY)) {
              uprofile.setBuildQuality(Double.valueOf(String.valueOf(object)));
            }
            else if (predicate.equals(HackystatVocab.COMMIT_FREQUENCY)) {
              uprofile.setCommitFrequency(Double.valueOf(String.valueOf(object)));
            }
            else if (predicate.equals(HackystatVocab.DEVELOPMENT_TIME)) {
              uprofile.setDevelopmentTime(Double.valueOf(String.valueOf(object)));
            }
            else if (predicate.equals(HackystatVocab.COMMUNICATION_EFFORT)) {
              uprofile.setCommunicationEffort(Double.valueOf(String.valueOf(object)));
            }
            else if (predicate.equals(FoafVocab.WEBLOG)) {
              uprofile.weblog = object;
            }
            else if (predicate.equals(DoapVocab.MAINTAINER)) {
              uprofile.addProjectRole(object, DoapVocab.MAINTAINER.getLocalName());
            }
            else if (predicate.equals(DoapVocab.TRANSLATOR)) {
              uprofile.addProjectRole(object, DoapVocab.TRANSLATOR.getLocalName());
            }
            else if (predicate.equals(DoapVocab.HELPER)) {
              uprofile.addProjectRole(object, DoapVocab.HELPER.getLocalName());
            }
            else if (predicate.equals(DoapVocab.DEVELOPER)) {
              uprofile.addProjectRole(object, DoapVocab.DEVELOPER.getLocalName());
            }
            else if (predicate.equals(DoapVocab.DOCUMENTER)) {
              uprofile.addProjectRole(object, DoapVocab.DOCUMENTER.getLocalName());
            }
            else if (predicate.equals(DoapVocab.TESTER)) {
              uprofile.addProjectRole(object, DoapVocab.TESTER.getLocalName());
            }
            else if (predicate.equals(RDFS.seeAlso)) {
              uprofile.addSeeAlsoUri(object);
            }
            else if (predicate.equals(OWL.sameAs)) {
              uprofile.addSameAsUri(object);
            }
            else if (predicate.equals(HackystatVocab.PRIVACY_LEVEL)) {
              uprofile.visibility = object;
            }
            else if (predicate.equals(FoafVocab.FIRST_NAME)) {
              uprofile.name = object;
            }
            else if (predicate.equals(FoafVocab.SURNAME)) {
              uprofile.surname = object;
            }
            else if (predicate.equals(HackystatVocab.KARMA)) {
              uprofile.karma = object;
            }
          }
          textlist = makeJTextFields(uprofile);
          profilesList.put(uprofile, textlist);
        }
      }
    }
    catch (LinkedServiceDataClientException e) {
      JOptionPane.showMessageDialog(this, e.getMessage(), "Hackystat - Error Message",
          JOptionPane.ERROR_MESSAGE);
      e.printStackTrace();
    }
    finally {
      disposeDialog();
    }
  }

  @Override
  public void keyPressed(KeyEvent e) {
    // TODO Auto-generated method stub

  }

  @Override
  public void keyReleased(KeyEvent e) {
    // TODO Auto-generated method stub

  }

  @Override
  public void keyTyped(KeyEvent e) {
    // TODO Auto-generated method stub

  }

  private void enableJTextFieldsToBeEdited(UserProfile profile) {
    LinkedList<JTextField> jtextfieldsList = null;
    if (profile != null && profilesList.containsKey(profile)) {
      jtextfieldsList = profilesList.get(profile);
      for (int i = 0; i < jtextfieldsList.size(); i++) {
        if (i == 0 || i == 1 || i == 3 || i == 4 || i == 5) {
          jtextfieldsList.get(i).setEditable(true);
          jtextfieldsList.get(i).setEnabled(true);
        }
      }
    }
  }

  private void disableAllJTextFields(UserProfile profile) {
    LinkedList<JTextField> jtextfieldsList = null;
    if (profile != null && profilesList.containsKey(profile)) {
      jtextfieldsList = profilesList.get(profile);
      for (JTextField field : jtextfieldsList) {
        field.setEditable(false);
      }
    }
  }

  private void disableAllJTextFields() {
    LinkedList<JTextField> jtextfieldsList = null;
    Iterator<UserProfile> it = profilesList.keySet().iterator();
    UserProfile profile = null;
    while (it.hasNext() && jtextfieldsList == null) {
      profile = it.next();
      jtextfieldsList = profilesList.get(profile);
      for (JTextField field : jtextfieldsList) {
        field.setEditable(false);
      }
    }
  }

  @Override
  public void actionPerformed(ActionEvent e) {
    Object source = e.getSource();
    String email = null;
    // System.out.println("ACTION PERFORMED!!");
    // System.out.println("e.getActionCommand()="+e.getActionCommand());
    if (source.equals(clearCacheButton)) {

      try {
        mainframe.clearServerCache();
      }
      catch (LinkedServiceDataClientException e1) {
        JOptionPane.showMessageDialog(this, e1.getMessage(), "Hackystat - Error Message",
            JOptionPane.ERROR_MESSAGE);
        e1.printStackTrace();
      }

    }
    else if (source.equals(triplifyAllButton)) {

      Iterator<Model> it = profilesModelList.iterator();
      Model model = null;
      if (it.hasNext()) {
        model = it.next();
      }
      while (it.hasNext()) {
        model = model.union(it.next());
      }
      String serializedModel = mainframe.getLiSeDClient().serializeRDFModel(model, this.language);
      displayRDFContentDialog(serializedModel);

    }
    else if (e.getActionCommand().startsWith(TRIPLIFYPREFIX)) {

      email = e.getActionCommand().split("_")[1];
      Iterator<Model> it = profilesModelList.iterator();
      String serializedModel = null;
      Model model = null;
      while (it.hasNext() && serializedModel == null) {
        model = it.next();
        if (model.contains(null, FoafVocab.MBOX, email)) {
          serializedModel = mainframe.getLiSeDClient().serializeRDFModel(model, this.language);
          displayRDFContentDialog(serializedModel);
        }
      }

    }
    else if (e.getActionCommand().startsWith(EDITPREFIX)) {

      if (userInEditingMode == null) {
        email = e.getActionCommand().split("_")[1];
        displayPasswordRequiredDialog(email);
      }
      else {
        JOptionPane.showMessageDialog(this, "You can't edit more than one user at a time",
            "Hackystat - Error Message", JOptionPane.ERROR_MESSAGE);
        return;
      }

    }
    else if (e.getActionCommand().startsWith(OKPREFIX)) {

      email = e.getActionCommand().split("_")[1];
      if (passwordText.getPassword() != null) {
        char[] passwd = passwordText.getPassword();
        password = "";
        for (int i = 0; i < passwd.length; i++) {
          password += passwd[i];
        }
        System.out.println("LinkedServiceDataClient Tracing: " + "SensorBaseClient.isRegistered("
            + email + ", " + password + ")");
        if (LinkedServiceDataClient.isRegistered(email, password)) {
          Iterator<UserProfile> it = profilesList.keySet().iterator();
          UserProfile profile = null, searchedProfile = null;
          while (it.hasNext() && searchedProfile == null) {
            profile = it.next();
            if (profile.email.equals(email)) {
              searchedProfile = profile;
            }
          }
          userInEditingMode = searchedProfile;
          enableJTextFieldsToBeEdited(userInEditingMode);
          JOptionPane.showMessageDialog(this, "Enter desired changes into the editable fields.",
              "Hackystat - Message", JOptionPane.PLAIN_MESSAGE);
          refresh();
        }
        else {
          JOptionPane.showMessageDialog(this, "You've entered a wrong password.",
              "Hackystat - Error Message", JOptionPane.ERROR_MESSAGE);
          return;
        }
      }
      else {
        JOptionPane.showMessageDialog(this, "Missing password", "Hackystat - Error Message",
            JOptionPane.ERROR_MESSAGE);
        return;
      }
      disposeDialog();
    }
    else if (e.getActionCommand().startsWith(SAVEPREFIX)) {
      email = e.getActionCommand().split("_")[1];
      LinkedList<JTextField> jtextfieldsList = null;
      User userObj = null;
      String visibility = null, nick = null, name = null, surname = null, homepage = null, weblog = null;
      jtextfieldsList = profilesList.get(userInEditingMode);
      userObj = new User();
      userObj.setEmail(email);
      visibility = jtextfieldsList.get(0).getText();
      String[] namesurname = jtextfieldsList.get(1).getText().split(" ");
      if (namesurname != null && namesurname.length >= 1) {
        name = namesurname[0];
        if (namesurname.length == 2) {
          surname = namesurname[1];
        }
      }
      nick = jtextfieldsList.get(3).getText();
      homepage = jtextfieldsList.get(4).getText();
      weblog = jtextfieldsList.get(5).getText();
      /**
       * To avoid an excessive increase of the user's properties length are posted only those
       * properties which have been actually modified.
       */
      if (!visibility.equals(userInEditingMode.visibility)) {
        userObj.addProperty(HackystatConstants.PROFILE_VISIBILITY, visibility);
      }
      if (name != null && !name.equals(userInEditingMode.name) && name.trim() != ""
          && name.trim() != "null") {
        userObj.addProperty(HackystatConstants.NAME, name);
      }
      if (surname != null && !surname.equals(userInEditingMode.surname) && surname.trim() != ""
          && surname.trim() != "null") {
        userObj.addProperty(HackystatConstants.SURNAME, surname);
      }
      if (nick != null && !nick.equals(userInEditingMode.nickname) && nick.trim() != ""
          && nick.trim() != "null") {
        userObj.addProperty(HackystatConstants.NICKNAME, nick);
      }
      if (homepage != null && !homepage.equals(userInEditingMode.homepage) && homepage.trim() != ""
          && homepage.trim() != "null") {
        userObj.addProperty(HackystatConstants.HOMEPAGE, homepage);
      }
      if (weblog != null && !weblog.equals(userInEditingMode.weblog) && weblog.trim() != ""
          && weblog.trim() != "null") {
        userObj.addProperty(HackystatConstants.WEBLOG, weblog);
      }
      userObj.setPassword(password);
      try {
        mainframe.getLiSeDClient().addUserData(userObj);
        JOptionPane.showMessageDialog(this, "Your new entered data have been saved.",
            "Hackystat - Message", JOptionPane.PLAIN_MESSAGE);
      }
      catch (LinkedServiceDataClientException e2) {
        JOptionPane.showMessageDialog(this, e2.getMessage(), "Hackystat - Error Message",
            JOptionPane.ERROR_MESSAGE);
        e2.printStackTrace();
        refreshProfiles();
      }
      disableAllJTextFields(userInEditingMode);
      userInEditingMode = null;
      refresh();

    }
    else if (source.equals(refreshButton)) {
      if (mainframe.isLogged()) {
        mainframe.getLiSeDClient().clearLocalCache();
        // JOptionPane.showMessageDialog(this, "Local cache for the logged user has been cleared.",
        // "Hackystat - Message", JOptionPane.PLAIN_MESSAGE);
        resetPanel();
      }
    }
    else if (source.equals(searchButton)) {
      new UserSearchWizard(mainframe);
    }
  }

  public void refresh() {
    this.removeAll();
    JPanel panel = new JPanel();
    panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
    panel.setBackground(Color.WHITE);
    if (mainframe.isLogged()) {
      clearCacheButton = new JButton("Clear cache", LinkedServiceDataUI.clearIcon);
      searchButton = new JButton("Search", LinkedServiceDataUI.searchIcon);
      refreshButton = new JButton("Refresh", LinkedServiceDataUI.refreshIcon);
      triplifyAllButton = new JButton("Triplify All", LinkedServiceDataUI.triplifyIcon);
      panel.add(mainframe.getHeader(this, searchButton, refreshButton, triplifyAllButton,
          clearCacheButton, "Users"));
    }

    JPanel subpanel = null;
    for (UserProfile profile : profilesList.keySet()) {
      subpanel = new JPanel();
      subpanel.setLayout(new BoxLayout(subpanel, BoxLayout.Y_AXIS));
      subpanel.setBackground(Color.WHITE);
      subpanel.add(Box.createVerticalStrut(10));
      LinkedList<JTextField> textlist = profilesList.get(profile);
      subpanel.add(fillInUserProfileData1(profile, textlist));
      subpanel.add(getActionsOnProfile(profile.email));
      subpanel.setBorder(BorderFactory.createLineBorder(Color.blue));
      panel.add(subpanel);
    }

    panel.setBackground(Color.white);
    JScrollPane listScrollPane = new JScrollPane(panel);
    listScrollPane = mainframe.initSubPanelScrollPane(listScrollPane);
    this.add(listScrollPane);
    this.validate();
  }

  private JPanel getActionsOnProfile(String email) {
    JPanel horiz = new JPanel();
    horiz.setLayout(new BoxLayout(horiz, BoxLayout.X_AXIS));
    horiz.add(Box.createHorizontalStrut(this.getSize().width / 2));
    horiz.setBackground(Color.white);
    actionLabel = new JLabel();
    actionLabel = mainframe.initLabel(actionLabel, "Actions:");
    horiz.add(actionLabel);
    horiz.add(Box.createHorizontalStrut(5));

    if (userInEditingMode != null && userInEditingMode.email.equals(email)) {
      saveButton = new JButton("Save");
      saveButton = mainframe.initButton(saveButton, this, mainframe.buttonDimension,
          "Save changes.");
      saveButton.setActionCommand(SAVEPREFIX + email);
      horiz.add(saveButton);
    }
    else {
      editButton = new JButton("Edit");
      editButton = mainframe.initButton(editButton, this, mainframe.buttonDimension,
          "Edit data about this user.");
      editButton.setActionCommand(EDITPREFIX + email);
      horiz.add(editButton);
      System.out.println("ADDED EDITBUTTON with ActionCommand=" + editButton.getActionCommand());
    }
    horiz.add(Box.createHorizontalStrut(5));

    triplifyOneButton = new JButton("Triplify", LinkedServiceDataUI.triplifyIcon);
    triplifyOneButton = mainframe.initButton(triplifyOneButton, this, mainframe.buttonDimension,
        "Get RDF representation of this user");
    triplifyOneButton.setActionCommand(TRIPLIFYPREFIX + email);
    horiz.add(triplifyOneButton);
    horiz.add(Box.createHorizontalGlue());
    return horiz;
  }

  private LinkedList<JTextField> makeJTextFields(UserProfile profile) {
    LinkedList<JTextField> textlist = new LinkedList<JTextField>();
    visibilityText = new JTextField(1);
    visibilityText = mainframe.initTextField(visibilityText, profile.visibility, false);
    textlist.add(visibilityText);
    nameSurnameText = new JTextField(10);
    nameSurnameText = mainframe.initTextField(nameSurnameText,
        profile.name + " " + profile.surname, false);
    textlist.add(nameSurnameText);
    emailText = new JTextField(10);
    emailText = mainframe.initTextField(emailText, profile.email, false);
    textlist.add(emailText);
    nickText = new JTextField(10);
    nickText = mainframe.initTextField(nickText, profile.nickname, false);
    textlist.add(nickText);
    homepageText = new JTextField(10);
    homepageText = mainframe.initTextField(homepageText, profile.homepage, false);
    textlist.add(homepageText);
    weblogText = new JTextField(10);
    weblogText = mainframe.initTextField(weblogText, profile.weblog, false);
    textlist.add(weblogText);

    return textlist;
  }

  /**
   * Monitor a correct displaying of this tab panel while the user is browsing between tabs. If he
   * is logged then the list of profiles for this panel is already updated and then it's not refresh
   * now.
   */
  public void prepareDisplaying() {
    if (!mainframe.isLogged()) {
      profilesList = new HashMap<UserProfile, LinkedList<JTextField>>();
    }
    else if (profilesList.isEmpty()) {
      refreshProfiles();
    }
    refresh();
  }

  /**
   * Forces the resetting of the whole panel and re-fills it only if the current user is logged.
   * This is used after changes to the authentication state.
   */
  public void resetPanel() {
    this.profilesList = new HashMap<UserProfile, LinkedList<JTextField>>();
    if (mainframe.isLogged()) {
      refreshProfiles();
    }
    refresh();
  }

  private JPanel fillInUserProfileData1(UserProfile profile, LinkedList<JTextField> textlist) {
    JPanel horiz = new JPanel();
    horiz.setLayout(new BoxLayout(horiz, BoxLayout.X_AXIS));
    horiz.setBackground(Color.white);
    JPanel vertic = null;
    initLabelHeaders1();

    vertic = new JPanel();
    vertic.setLayout(new BoxLayout(vertic, BoxLayout.Y_AXIS));
    vertic.setBackground(Color.white);
    vertic.add(visibilityLabel);
    vertic.add(Box.createVerticalStrut(1));
    vertic.add(textlist.get(0));
    vertic.add(Box.createVerticalStrut(3));
    vertic.add(nameSurnameLabel);
    vertic.add(Box.createVerticalStrut(1));
    vertic.add(textlist.get(1));
    vertic.add(Box.createVerticalStrut(3));
    vertic.add(karmaLabel);
    vertic.add(Box.createVerticalStrut(1));
    karmaText = new JTextField(10);
    String value = profile.karma;
    if (value == null) {
      value = "NA";
    }
    karmaText = mainframe.initTextField(karmaText, value, false);
    vertic.add(karmaText);
    horiz.add(vertic);

    vertic = new JPanel();
    vertic.setLayout(new BoxLayout(vertic, BoxLayout.Y_AXIS));
    vertic.setBackground(Color.white);
    vertic.add(emailLabel);
    vertic.add(Box.createVerticalStrut(1));
    vertic.add(textlist.get(2));
    vertic.add(Box.createVerticalStrut(3));
    vertic.add(skillsLabel);
    vertic.add(Box.createVerticalStrut(1));
    DefaultListModel listModel = new DefaultListModel();
    for (String skill : profile.getSkills().keySet()) {
      value = String.valueOf(profile.getSkills().get(skill));
      if (value.equals("-1.0")) {
        value = "NA";
      }
      listModel.addElement(skill + " - " + value);
    }
    listSkills = new JList(listModel);
    listSkills.setOpaque(true);
    listSkills.setFont(new Font("Dialog", Font.PLAIN, 13));
    listSkills.setBackground(Color.white);
    JScrollPane listScrollPane = new JScrollPane(listSkills);
    listScrollPane.setPreferredSize(mainframe.jlistDimension);
    listScrollPane.setMaximumSize(mainframe.jlistDimension);
    listScrollPane.setMinimumSize(mainframe.jlistDimension);
    vertic.add(listScrollPane);
    horiz.add(vertic);

    vertic = new JPanel();
    vertic.setLayout(new BoxLayout(vertic, BoxLayout.Y_AXIS));
    vertic.setBackground(Color.white);
    vertic.add(nickLabel);
    vertic.add(Box.createVerticalStrut(1));
    vertic.add(textlist.get(3));
    vertic.add(Box.createVerticalStrut(3));
    vertic.add(seeAlsoLabel);
    vertic.add(Box.createVerticalStrut(1));
    listModel = new DefaultListModel();
    for (String seeAlso : profile.getSeeAlso()) {
      listModel.addElement(seeAlso);
    }
    listSeeAlso = new JList(listModel);
    listSeeAlso.setOpaque(true);
    listSeeAlso.setFont(new Font("Dialog", Font.PLAIN, 13));
    listSeeAlso.setBackground(Color.white);
    listScrollPane = new JScrollPane(listSeeAlso);
    listScrollPane.setPreferredSize(mainframe.jlistDimension);
    listScrollPane.setMaximumSize(mainframe.jlistDimension);
    listScrollPane.setMinimumSize(mainframe.jlistDimension);
    vertic.add(listScrollPane);
    horiz.add(vertic);

    vertic = new JPanel();
    vertic.setLayout(new BoxLayout(vertic, BoxLayout.Y_AXIS));
    vertic.setBackground(Color.white);
    vertic.add(homepageLabel);
    vertic.add(Box.createVerticalStrut(1));
    vertic.add(textlist.get(4));
    vertic.add(Box.createVerticalStrut(3));
    vertic.add(sameAsLabel);
    vertic.add(Box.createVerticalStrut(1));
    listModel = new DefaultListModel();
    for (String sameAs : profile.getSameAs()) {
      listModel.addElement(sameAs);
    }
    listSameAs = new JList(listModel);
    listSameAs.setOpaque(true);
    listSameAs.setFont(new Font("Dialog", Font.PLAIN, 13));
    listSameAs.setBackground(Color.white);
    listScrollPane = new JScrollPane(listSameAs);
    listScrollPane.setPreferredSize(mainframe.jlistDimension);
    listScrollPane.setMaximumSize(mainframe.jlistDimension);
    listScrollPane.setMinimumSize(mainframe.jlistDimension);
    vertic.add(listScrollPane);
    horiz.add(vertic);

    vertic = new JPanel();
    vertic.setLayout(new BoxLayout(vertic, BoxLayout.Y_AXIS));
    vertic.setBackground(Color.white);
    vertic.add(weblogLabel);
    vertic.add(Box.createVerticalStrut(1));
    vertic.add(textlist.get(5));
    vertic.add(Box.createVerticalStrut(3));
    vertic.add(projectsrolesLabel);
    vertic.add(Box.createVerticalStrut(2));
    listModel = new DefaultListModel();
    for (String[] projRol : profile.getProjectsRoles()) {
      listModel.addElement(projRol[0] + " - " + projRol[1]);
    }
    listProjectsRoles = new JList(listModel);
    listProjectsRoles.setOpaque(true);
    listProjectsRoles.setFont(new Font("Dialog", Font.PLAIN, 13));
    listProjectsRoles.setBackground(Color.white);
    listScrollPane = new JScrollPane(listProjectsRoles);
    listScrollPane.setPreferredSize(mainframe.jlistDimension);
    listScrollPane.setMaximumSize(mainframe.jlistDimension);
    listScrollPane.setMinimumSize(mainframe.jlistDimension);
    vertic.add(listScrollPane);
    horiz.add(vertic);
    return horiz;
  }

  private void initLabelHeaders1() {
    visibilityLabel = new JLabel();
    visibilityLabel = mainframe.initLabel(visibilityLabel, "Visibility:");

    nameSurnameLabel = new JLabel();
    nameSurnameLabel = mainframe.initLabel(nameSurnameLabel, "Name and Surname:");

    emailLabel = new JLabel();
    emailLabel = mainframe.initLabel(emailLabel, "Email:");

    nickLabel = new JLabel();
    nickLabel = mainframe.initLabel(nickLabel, "Nickname:");

    homepageLabel = new JLabel();
    homepageLabel = mainframe.initLabel(homepageLabel, "Homepage:");

    weblogLabel = new JLabel();
    weblogLabel = mainframe.initLabel(weblogLabel, "Weblog:");

    karmaLabel = new JLabel();
    karmaLabel = mainframe.initLabel(karmaLabel, "Karma:");

    skillsLabel = new JLabel();
    skillsLabel = mainframe.initLabel(skillsLabel, "Skills:");

    seeAlsoLabel = new JLabel();
    seeAlsoLabel = mainframe.initLabel(seeAlsoLabel, "See also:");

    sameAsLabel = new JLabel();
    sameAsLabel = mainframe.initLabel(sameAsLabel, "Same as:");

    projectsrolesLabel = new JLabel();
    projectsrolesLabel = mainframe.initLabel(projectsrolesLabel, "Projects/Roles:");
  }

  public void displayWaitingDialog() {
    JProgressBar pb = new JProgressBar(0, 100);
    pb.setPreferredSize(new Dimension(175, 20));
    pb.setString("wait");
    pb.setIndeterminate(true);
    pb.setStringPainted(true);
    pb.setValue(0);
    JLabel label = new JLabel("The list of users is being downloaded "
        + "from LiSeD service. Please wait...");
    JPanel center_panel = new JPanel();
    center_panel.setLayout(new BoxLayout(center_panel, BoxLayout.Y_AXIS));
    center_panel.add(label);
    center_panel.add(Box.createVerticalStrut(2));
    center_panel.add(pb);
    dialog = new JDialog(mainframe, "Please wait...");

    dialog.setLocationRelativeTo(null); // center on screen
    dialog.setLocation(550, 25); // position by coordinates
    dialog.toFront(); // raise above other java windows

    dialog.getContentPane().add(center_panel, BorderLayout.CENTER);
    dialog.pack();
    dialog.setVisible(true);
    this.setEnabled(false);
    mainframe.setEnabled(false);
    dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
    dialog.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent we) {
        setEnabled(true);
        mainframe.setEnabled(true);
        dialog.dispose();
        dialog = null;
      }
    });
    // dialog.setBackground(Color.white);
  }

  public void disposeDialog() {
    this.setEnabled(true);
    mainframe.setEnabled(true);
    if (dialog != null) {
      dialog.dispose();
    }
  }

  public void displayPasswordRequiredDialog(String email) {
    JPanel center_panel = new JPanel();
    center_panel.setLayout(new BoxLayout(center_panel, BoxLayout.Y_AXIS));
    JLabel label = new JLabel("Insert the selected user's password:");
    center_panel.add(label);
    center_panel.add(Box.createVerticalStrut(2));
    passwordText = new JPasswordField();
    center_panel.add(passwordText);
    center_panel.add(Box.createVerticalStrut(5));
    okButton = new JButton();
    okButton.setMnemonic(KeyEvent.VK_S);
    okButton.setFont(new Font("Dialog", java.awt.Font.BOLD, mainframe.buttonFontSize));
    okButton.setText("OK");
    okButton.addActionListener(this);
    okButton.setSize(mainframe.triplifyButtonDimension);
    okButton.setPreferredSize(mainframe.triplifyButtonDimension);
    okButton.setMaximumSize(mainframe.triplifyButtonDimension);
    okButton.setMinimumSize(mainframe.triplifyButtonDimension);
    okButton.setActionCommand(OKPREFIX + email);
    center_panel.add(okButton);

    dialog = new JDialog(mainframe, "Insert Password");

    dialog.setLocationRelativeTo(null); // center on screen
    // dialog.setLocation(550,25); // position by coordinates
    dialog.toFront(); // raise above other java windows

    dialog.getContentPane().add(center_panel, BorderLayout.CENTER);
    dialog.pack();
    dialog.setVisible(true);
    this.setEnabled(false);
    mainframe.setEnabled(false);
    dialog.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent we) {
        setEnabled(true);
        mainframe.setEnabled(true);
        dialog.dispose();
        dialog = null;
      }
    });
    dialog.setBackground(Color.white);
  }

  public void displayRDFContentDialog(String serializedModel) {
    JTextArea area = new JTextArea(serializedModel);
    area.setColumns(mainframe.jdialogTextAreaNumCols);
    area.setRows(mainframe.jdialogTextAreaNumRows);
    area.setEditable(false);
    JScrollPane listScrollPane = new JScrollPane(area);
    listScrollPane.setPreferredSize(mainframe.jdialogAreaDimension);
    listScrollPane.setMaximumSize(mainframe.jdialogAreaDimension);
    listScrollPane.setMinimumSize(mainframe.jdialogAreaDimension);
    JLabel label = new JLabel("RDF serialization using the language " + this.language);
    JPanel center_panel = new JPanel();
    center_panel.setLayout(new BoxLayout(center_panel, BoxLayout.Y_AXIS));
    center_panel.add(label);
    center_panel.add(Box.createVerticalStrut(5));
    center_panel.add(listScrollPane);
    JDialog dialog1 = new JDialog(mainframe, "RDF User Profiles");

    dialog1.setLocationRelativeTo(null); // center on screen
    dialog1.setLocation(550, 25); // position by coordinates
    dialog1.toFront(); // raise above other java windows

    dialog1.getContentPane().add(center_panel, BorderLayout.CENTER);
    dialog1.pack();
    dialog1.setVisible(true);

    dialog1.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
  }
}
